//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "ProviderDlg.h"
#include "FormUtilities.h"
#include "Calendar.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"

const int CODE_NAME = 1;

//---------------------------------------------------------------------------

__fastcall TfrmProviderDlg::TfrmProviderDlg(TComponent* Owner, TProviderBridge* bridge, TProvider* provider)
        : TForm(Owner)
{
   TFormUtilities::LocateForm(( TForm*)Owner, this);

   this->bridge   = bridge;
   this->provider = provider;

   if ( provider == NULL)
   {
      Caption = "Add new provider";
   }
   else
   {
      Caption = "Update provider";
      ShowProvider();
   }//if-else
}

void TfrmProviderDlg :: ShowProvider()
{
   edtName->Text = provider->name;
   edtAddress->Text = provider->address;
   edtPhone->Text = provider->phone;
}

void TfrmProviderDlg :: GatherProvider()
{
   provider->name = edtName->Text;
   provider->address = edtAddress->Text;
   provider->phone = edtPhone->Text;
}

void TfrmProviderDlg :: AddNewProvider()
{
   provider = new TProvider();

   try
   {
      GatherProvider();
      bridge->Add( provider);
   }
   __finally
   {
      delete provider;
      provider = NULL;
   }//try-finally
}

void TfrmProviderDlg :: UpdateProvider()
{
   GatherProvider();
   bridge->Update( provider);
}

void TfrmProviderDlg :: ValidateData()
{
   if ( edtName->Text.Length() == 0)
      throw new TError( CODE_NAME, "Provider name must be entered");

   if ( edtName->Text.Length() > 128)
      throw new TError( CODE_NAME, "Provider name too long");
}

void TfrmProviderDlg :: HandleError( TError * e)
{
   MessageDlg( e->Message,
               mtError,
               TMsgDlgButtons() << mbOK,
               0);

   switch ( e->GetCode())
   {
      case CODE_NAME :
         edtName->SetFocus();
         break;
   }//switch

   ModalResult = mrNone;
}

void __fastcall TfrmProviderDlg::btnOKClick(TObject *Sender)
{
   try
   {
      ValidateData();

      if ( provider == NULL)
         AddNewProvider();
      else
         UpdateProvider();
   }
   catch( TError * e)
   {
      HandleError( e);
   }//try-catch
}

